package com.hongshu.idle.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hongshu.common.core.validator.ValidatorUtil;
import com.hongshu.idle.domain.Query;
import com.hongshu.idle.domain.entity.IdleCategory;
import com.hongshu.idle.domain.entity.IdleProduct;
import com.hongshu.idle.domain.entity.IdleProductOrder;
import com.hongshu.idle.mapper.idle.IdleCategoryMapper;
import com.hongshu.idle.mapper.idle.IdleProductMapper;
import com.hongshu.idle.mapper.idle.IdleProductOrderMapper;
import com.hongshu.idle.service.sys.ISysIdleProductOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 闲宝信息 服务层处理
 *
 * @author hongshu
 */
@Slf4j
@Service
public class SysIdleProductOrderServiceImpl implements ISysIdleProductOrderService {

    @Autowired
    private IdleCategoryMapper categoryMapper;
    @Autowired
    private IdleProductMapper productMapper;
    @Autowired
    private IdleProductOrderMapper orderMapper;


    @Override
    public Map<String, Object> getOrderDataByWeek() {
        Map<String, Object> result = new HashMap<>();
        Map<String, List<Integer>> categoryData = new HashMap<>();      // 分类名称 → 数据列表
        Map<String, String> categoryIdMap = new HashMap<>();            // 分类名称 → id（辅助映射）

        // 1. 获取最近7天的日期和所有分类
        List<String> dateList = getLast7Days();
        List<IdleCategory> categoryList = categoryMapper.selectList(new QueryWrapper<>());

        // 2. 初始化数据结构
        for (IdleCategory category : categoryList) {
            String categoryName = category.getTitle();
            categoryData.put(categoryName, new ArrayList<>());
            categoryIdMap.put(categoryName, category.getId());  // 记录名称对应的id
        }

        // 3. 填充每日数据
        for (String date : dateList) {
            for (IdleCategory category : categoryList) {
                String categoryName = category.getTitle();
                String categoryId = category.getId();
                int count = orderMapper.countOrdersByCategoryAndDate(date, categoryId);
                categoryData.get(categoryName).add(count);
            }
        }

        // 4. 返回结果
        result.put("dates", dateList);
        result.put("categoryData", categoryData);
        result.put("categoryIdMap", categoryIdMap);  // 可选：提供分类名称到id的映射
        return result;
    }

    @Override
    public List<IdleProductOrder> selectOrderList(Query query) {
        // 1. 查询订单列表
        QueryWrapper<IdleProductOrder> qw = new QueryWrapper<>();

        // 动态条件（如 order_number, beginTime, endTime）
        String orderNumber = (String) query.get("orderNumber");
        if (ValidatorUtil.isNotNull(orderNumber)) {
            qw.lambda().like(IdleProductOrder::getOrderNumber, orderNumber);
        }

        // 时间范围查询
        String beginTimeStr = (String) query.get("params[beginTime]");
        String endTimeStr = (String) query.get("params[endTime]");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        if (ValidatorUtil.isNotNull(beginTimeStr)) {
            try {
                Date beginTime = sdf.parse(beginTimeStr);
                qw.lambda().ge(IdleProductOrder::getCreateTime, beginTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (ValidatorUtil.isNotNull(endTimeStr)) {
            try {
                Date endTime = sdf.parse(endTimeStr);
                endTime = new Date(endTime.getTime() + 1000 * 60 * 60 * 24 - 1);
                qw.lambda().le(IdleProductOrder::getCreateTime, endTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 排序
        qw.lambda().orderByDesc(IdleProductOrder::getUpdateTime);

        // 执行查询
        List<IdleProductOrder> orderList = orderMapper.selectList(qw);

        // 2. 提取所有 productId
        Set<String> productIds = orderList.stream()
                .map(IdleProductOrder::getProductId)
                .collect(Collectors.toSet());

        // 3. 批量查询商品信息
        if (!productIds.isEmpty()) {
            List<IdleProduct> productList = productMapper.selectBatchIds(productIds);
            Map<String, IdleProduct> productMap = productList.stream()
                    .collect(Collectors.toMap(IdleProduct::getId, p -> p));

            // 4. 填充 productTitle 和 productCover
            orderList.forEach(order -> {
                IdleProduct product = productMap.get(order.getProductId());
                if (product != null) {
                    order.setProductTitle(product.getTitle());
                    order.setProductCover(product.getCover());
                }
            });
        }

        return orderList;
    }

    @Override
    public IdleProductOrder selectOrderById(Long id) {
        IdleProductOrder idleProductOrder = orderMapper.selectById(id);
        IdleProduct idleProduct = productMapper.selectById(idleProductOrder.getProductId());
        idleProductOrder.setProductCover(idleProduct.getCover());
        return idleProductOrder;
    }

    @Override
    public int deleteOrderByIds(Long[] ids) {
        List<Long> longs = Arrays.asList(ids);
        for (Long id : ids) {
            IdleProductOrder order = orderMapper.selectById(id);
            if (ValidatorUtil.isNull(order)) {
                log.info("订单不存在:{}", id);
                longs.remove(id);
            }
        }
        return orderMapper.deleteBatchIds(longs);
    }

    /**
     * 获取最近7天的日期和所有分类
     */
    private List<String> getLast7Days() {
        List<String> dateList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        for (int i = 6; i >= 0; i--) {
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -i);
            dateList.add(sdf.format(calendar.getTime()));
        }
        return dateList;
    }
}
